<template>
  <div class="wallpaper-container">
    <div class="wallpaper-content">
      <!-- 标题区域 -->
      <div class="header-section">
        <div class="title-container">
          <div class="emoji-container">🎬</div>
          <h1 class="main-title">动态壁纸生成器</h1>
          <div class="emoji-container">✨</div>
        </div>
        <p class="subtitle">随机生成高质量动态壁纸，适用于桌面和手机</p>
      </div>

      <!-- 视频预览区域 -->
      <div class="preview-section">
        <div class="video-wrapper" :class="{ 'has-video': wallpaperData && videoReady }">
          <div v-if="!wallpaperData || !videoReady" class="placeholder-container">
            <div v-if="loading" class="loading-placeholder">
              <a-spin :indicator="spinIcon" />
              <p>正在获取精美壁纸...</p>
            </div>
            <div v-else class="empty-placeholder">
              <play-circle-outlined />
              <p>点击下方按钮生成壁纸</p>
            </div>
          </div>

          <video
            v-if="wallpaperData"
            ref="videoPlayer"
            class="video-player"
            :src="wallpaperData.video_url"
            controls
            autoplay
            loop
            muted
            @loadeddata="videoLoaded"
            @error="videoError"
          ></video>

          <div class="video-controls" v-if="wallpaperData && videoReady">
            <a-button
              type="primary"
              shape="circle"
              size="large"
              class="control-btn refresh-btn"
              @click="generateWallpaper"
              :loading="loading"
              title="生成新壁纸"
            >
              <template #icon><reload-outlined /></template>
            </a-button>

            <a-button
              type="primary"
              shape="circle"
              size="large"
              class="control-btn download-btn"
              @click="downloadWallpaper"
              title="下载壁纸"
            >
              <template #icon><download-outlined /></template>
            </a-button>

            <a-button
              type="primary"
              shape="circle"
              size="large"
              class="control-btn copy-btn"
              @click="copyVideoUrl"
              title="复制链接"
            >
              <template #icon><link-outlined /></template>
            </a-button>
          </div>
        </div>
      </div>

      <!-- 操作区域 -->
      <div class="action-section">
        <a-button
          type="primary"
          size="large"
          :loading="loading"
          @click="generateWallpaper"
          class="generate-btn"
          :disabled="loading"
        >
          <template #icon><thunderbolt-outlined /></template>
          {{ wallpaperData ? '换一个壁纸' : '生成壁纸' }}
        </a-button>
      </div>

      <!-- API响应信息 -->
      <a-collapse v-if="wallpaperData" class="api-info-section">
        <a-collapse-panel key="1" header="API响应信息">
          <div class="api-info-content">
            <div class="api-info-item">
              <div class="api-info-label">状态:</div>
              <div class="api-info-value">
                <a-tag :color="wallpaperData.success ? 'success' : 'error'">
                  {{ wallpaperData.success ? '成功' : '失败' }}
                </a-tag>
              </div>
            </div>

            <div class="api-info-item">
              <div class="api-info-label">消息:</div>
              <div class="api-info-value">{{ wallpaperData.message }}</div>
            </div>

            <div class="api-info-item">
              <div class="api-info-label">视频URL:</div>
              <div class="api-info-value url-value">
                <a-tooltip :title="wallpaperData.video_url">
                  <span class="truncated-url">{{ wallpaperData.video_url }}</span>
                </a-tooltip>
                <a-button
                  type="text"
                  size="small"
                  @click="copyVideoUrl"
                >
                  <template #icon><copy-outlined /></template>
                  复制
                </a-button>
              </div>
            </div>
          </div>
        </a-collapse-panel>
      </a-collapse>

      <!-- 错误提示 -->
      <div v-if="error" class="error-section">
        <a-alert
          :message="error"
          type="error"
          show-icon
          closable
          @close="error = ''"
        />
      </div>

      <!-- 使用提示 -->
      <div class="tips-section">
        <a-alert
          message="如何使用动态壁纸"
          description="下载视频后，可以在Windows 10/11的个性化设置中选择'背景'，然后选择'幻灯片放映'，并添加下载的视频文件。在Android手机上，可以使用第三方应用如'视频动态壁纸'设置。在iPhone上，可以通过'设置 > 墙纸 > 选择新墙纸 > 实况照片'来设置。"
          type="info"
          show-icon
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted, h } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import {
  ThunderboltOutlined,
  DownloadOutlined,
  CopyOutlined,
  PlayCircleOutlined,
  ReloadOutlined,
  LinkOutlined,
  LoadingOutlined
} from '@ant-design/icons-vue';

// 状态定义
const wallpaperData = ref(null);
const loading = ref(false);
const error = ref('');
const videoPlayer = ref(null);
const videoReady = ref(false);

// 自定义加载图标
const spinIcon = reactive(h(LoadingOutlined, { style: { fontSize: '36px' } }));

// 生成壁纸
const generateWallpaper = async () => {
  loading.value = true;
  error.value = '';
  videoReady.value = false;

  try {
    const apiUrl = 'https://api.hn/video.php?return=json';
    const response = await axios.get(apiUrl, {
      timeout: 15000
    });

    console.log('壁纸响应:', response);

    if (response.data && response.data.success) {
      wallpaperData.value = response.data;
      message.success('壁纸获取成功');
    } else {
      error.value = response.data?.message || '获取壁纸失败';
      message.error(error.value);
    }
  } catch (err) {
    console.error('获取壁纸失败:', err);
    error.value = `网络错误: ${err.message}`;
    message.error(error.value);
  } finally {
    loading.value = false;
  }
};

// 视频加载完成
const videoLoaded = () => {
  videoReady.value = true;
};

// 视频加载错误
const videoError = () => {
  videoReady.value = false;
  error.value = '视频加载失败，请重试';
  message.error(error.value);
};

// 下载壁纸
const downloadWallpaper = () => {
  if (!wallpaperData.value || !wallpaperData.value.video_url) {
    message.warning('没有可下载的壁纸');
    return;
  }

  try {
    // 创建一个临时链接
    const link = document.createElement('a');
    link.href = wallpaperData.value.video_url;

    // 从URL中提取文件名，如果无法提取则使用默认名称
    const urlParts = wallpaperData.value.video_url.split('/');
    const fileName = urlParts[urlParts.length - 1] || 'dynamic-wallpaper.mp4';

    link.download = fileName;

    // 添加到文档并触发点击
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);

    message.success('壁纸下载已开始');
  } catch (err) {
    console.error('下载失败:', err);
    message.error('下载失败，请重试或直接复制链接');
  }
};

// 复制视频URL
const copyVideoUrl = () => {
  if (!wallpaperData.value || !wallpaperData.value.video_url) {
    message.warning('没有可复制的链接');
    return;
  }

  try {
    navigator.clipboard.writeText(wallpaperData.value.video_url).then(() => {
      message.success('链接已复制到剪贴板');
    }, () => {
      message.error('复制失败，请手动复制');
    });
  } catch (err) {
    console.error('复制失败:', err);
    message.error('复制失败，请手动复制');
  }
};

// 组件卸载时停止视频播放
onUnmounted(() => {
  if (videoPlayer.value) {
    videoPlayer.value.pause();
  }
});
</script>

<style scoped>
.wallpaper-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.wallpaper-content {
  max-width: 900px;
  width: 100%;
  background-color: white;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 30px;
  margin-top: 20px;
}

/* 标题区域 */
.header-section {
  text-align: center;
  margin-bottom: 30px;
}

.title-container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.emoji-container {
  font-size: 2.5rem;
  margin: 0 15px;
  animation: float 3s ease-in-out infinite;
}

.emoji-container:first-child {
  animation-delay: 0.2s;
}

.emoji-container:last-child {
  animation-delay: 0.4s;
}

@keyframes float {
  0% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
  100% { transform: translateY(0px); }
}

.main-title {
  font-size: 2.5rem;
  font-weight: bold;
  margin: 0;
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
}

.subtitle {
  color: #666;
  font-size: 1.1rem;
  margin-top: 5px;
}

/* 视频预览区域 */
.preview-section {
  margin-bottom: 30px;
}

.video-wrapper {
  position: relative;
  width: 100%;
  border-radius: 15px;
  overflow: hidden;
  background-color: #f0f2f5;
  aspect-ratio: 16 / 9;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.video-wrapper.has-video {
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.placeholder-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #666;
}

.loading-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.loading-placeholder p {
  margin: 0;
  font-size: 1.1rem;
}

.empty-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.empty-placeholder svg {
  font-size: 4rem;
  color: #d9d9d9;
}

.empty-placeholder p {
  margin: 0;
  font-size: 1.1rem;
  color: #999;
}

.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.video-controls {
  position: absolute;
  bottom: 20px;
  right: 20px;
  display: flex;
  gap: 10px;
  opacity: 0;
  transform: translateY(10px);
  transition: all 0.3s ease;
}

.video-wrapper:hover .video-controls {
  opacity: 1;
  transform: translateY(0);
}

.control-btn {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.refresh-btn {
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  border: none;
}

.download-btn {
  background: linear-gradient(45deg, #11998e, #38ef7d);
  border: none;
}

.copy-btn {
  background: linear-gradient(45deg, #f5af19, #f12711);
  border: none;
}

/* 操作区域 */
.action-section {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.generate-btn {
  height: 50px;
  font-size: 1.2rem;
  padding: 0 40px;
  border-radius: 25px;
  background: linear-gradient(45deg, #6a11cb, #2575fc);
  border: none;
  box-shadow: 0 5px 15px rgba(106, 17, 203, 0.3);
  transition: all 0.3s ease;
}

.generate-btn:hover:not(:disabled) {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(106, 17, 203, 0.4);
}

.generate-btn:active:not(:disabled) {
  transform: translateY(-1px);
}

/* API信息区域 */
.api-info-section {
  margin-bottom: 30px;
  border-radius: 10px;
  overflow: hidden;
}

.api-info-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.api-info-item {
  display: flex;
  align-items: flex-start;
}

.api-info-label {
  width: 80px;
  font-weight: bold;
  color: #666;
}

.api-info-value {
  flex: 1;
}

.url-value {
  display: flex;
  align-items: center;
  gap: 10px;
}

.truncated-url {
  max-width: 500px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #1890ff;
  cursor: pointer;
}

/* 错误区域 */
.error-section {
  margin-bottom: 30px;
}

/* 提示区域 */
.tips-section {
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wallpaper-content {
    padding: 20px;
    border-radius: 15px;
  }

  .main-title {
    font-size: 2rem;
  }

  .emoji-container {
    font-size: 2rem;
    margin: 0 10px;
  }

  .subtitle {
    font-size: 1rem;
  }

  .video-controls {
    bottom: 15px;
    right: 15px;
  }

  .control-btn {
    width: 45px;
    height: 45px;
  }

  .generate-btn {
    width: 100%;
    padding: 0 20px;
  }

  .api-info-item {
    flex-direction: column;
    gap: 5px;
  }

  .api-info-label {
    width: 100%;
  }

  .truncated-url {
    max-width: 200px;
  }
}
</style>
